import {Shader} from "./Shader";
import {App} from "./App";
import {Camera} from "./Camera";

export class Mesh{

    _shader:Shader;
    _vao:WebGLVertexArrayObject;
    _vertexCount = 0;
    public constructor(v:Float32Array) {
        let gl = App.instance().gl;
        this._vertexCount = v.length / 3;

        let shaderCache = App.instance().shaderCache;
        let shader =  this._shader = shaderCache.get('line');

        //
        let vao = this._vao = gl.createVertexArray() as WebGLVertexArrayObject;
        gl.bindVertexArray(vao);

        let vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,vbo);
        gl.bufferData(gl.ARRAY_BUFFER,v,gl.STATIC_DRAW);
        gl.enableVertexAttribArray(shader.attribs['a_position']);
        gl.vertexAttribPointer(shader.attribs['a_position'],3,gl.FLOAT,false,0,0);
        gl.bindVertexArray(null);
    }

    public draw(gl:WebGL2RenderingContext,camera:Camera){
        this._shader.bind();

        this._shader.setMat4('u_projMatrix',camera.projMat);
        this._shader.setMat4('u_vmMatrix',camera.viewMat);

        gl.bindVertexArray(this._vao);
        gl.drawArrays(gl.TRIANGLES,0,this._vertexCount);
        gl.bindVertexArray(null);
        this._shader.unbind();
    }
}
